<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import ReSlider from "@/components/ReSlider/index.vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { setToken } from "@/utils/auth";
import { addPathMatch, getTopMenu } from "@/router/utils";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useUserStoreHook } from "@/store/modules/user";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const loginType = ref("password"); // 登录方式：password-密码登录，sms-短信登录

const ruleForm = reactive({
  username: localStorage.getItem("remember_username") || "15888888888",
  password: localStorage.getItem("remember_password") || "123456",
  code: "",
  smsCode: "", // 短信验证码
  entrySide: "2",
  entryType: "1",
  uuid: ""
});

const rememberPassword = ref(!!localStorage.getItem("remember_username")); // 是否记住密码

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        const user = await useUserStoreHook().login({
          ...ruleForm,
          loginType: loginType.value,
          code: loginType.value === "sms" ? ruleForm.smsCode : ruleForm.code
        });
        if (user) {
          // 保存记住的用户名和密码
          if (rememberPassword.value) {
            localStorage.setItem("remember_username", ruleForm.username);
            localStorage.setItem("remember_password", ruleForm.password);
          } else {
            localStorage.removeItem("remember_username");
            localStorage.removeItem("remember_password");
          }
          // 全部采取静态路由模式
          usePermissionStoreHook().handleWholeMenus([]);
          addPathMatch();
          router.push("/");
          // router.push(getTopMenu(true).path);
          message("登录成功", { type: "success" });
        } else {
          // 全部采取静态路由模式
          usePermissionStoreHook().handleWholeMenus([]);
          addPathMatch();
          router.push("/");
          message("登录失败");
        }
      } catch (error) {
        message(error.msg, { type: "warning" });
      } finally {
        loading.value = false;
      }
    } else {
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

const handleSliderSuccess = () => {
  ruleForm.code = "SLIDER_VERIFIED";
};

const smsLoading = ref(false);
const countdown = ref(0);
let timer: NodeJS.Timeout | null = null;

async function getSmsCode() {
  if (smsLoading.value || countdown.value > 0) return;
  if (!ruleForm.username) {
    message("请输入手机号", { type: "warning" });
    return;
  }
  smsLoading.value = true;
  try {
    await useUserStoreHook().getSmsCode(ruleForm.username);
    message("验证码已发送", { type: "success" });
    countdown.value = 60;
    timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
      }
    }, 1000);
  } catch (error) {
    message(error.msg || "获取验证码失败", { type: "error" });
  } finally {
    smsLoading.value = false;
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
  // getcodeimg();
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="absolute flex-c right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <div class="login-type-switch mb-4">
            <el-radio-group v-model="loginType" size="large">
              <el-radio-button label="password">密码登录</el-radio-button>
              <el-radio-button label="sms">短信登录</el-radio-button>
            </el-radio-group>
          </div>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入手机号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="手机号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion v-if="loginType === 'password'" :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion v-if="loginType === 'password'" :delay="150">
              <el-form-item>
                <re-slider @success="handleSliderSuccess" />
              </el-form-item>
            </Motion>

            <Motion v-if="loginType === 'sms'" :delay="150">
              <div class="flex justify-between items-center">
                <div class="flex-1 pr-2">
                  <el-form-item prop="smsCode">
                    <el-input
                      v-model="ruleForm.smsCode"
                      clearable
                      placeholder="短信验证码"
                      @keyup.enter="onLogin(ruleFormRef)"
                    />
                  </el-form-item>
                </div>
                <el-button
                  type="primary"
                  :loading="smsLoading"
                  :disabled="countdown > 0"
                  style="width: 120px; margin-bottom: 20px"
                  @click="getSmsCode"
                >
                  {{ countdown > 0 ? `${countdown}s后重试` : "获取验证码" }}
                </el-button>
              </div>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
            <Motion :delay="200">
              <el-checkbox
                v-model="rememberPassword"
                class="w-full mt-4"
                size="large"
              >
                记住密码
              </el-checkbox>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
